<template>
  <div>
    <a-page-header
      style="border: 1px solid rgb(235, 237, 240)"
      title="新建活动"
      :ghost="false"
      @back="() => $router.go(-1)"
    ></a-page-header>

    <page-header-wrapper>
      <a-card :bordered="false">
        <a-form-model ref="form" :model="form" :rules="formRules" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
          <h3 class="title">活动设置</h3>
          <a-form-model-item label="活动名称" prop="name">
            <a-input v-model="form.name" placeholder="请输入活动名称" class="maxWidth" />
          </a-form-model-item>

          <a-form-model-item label="活动日期" prop="queryTime">
            <a-range-picker
              show-time
              class="maxWidth"
              format="YYYY-MM-DD HH:mm:ss"
              valueFormat="YYYY-MM-DD HH:mm:ss"
              :placeholder="['开始时间', '结束时间']"
              v-model="form.queryTime"
            />
          </a-form-model-item>

          <a-divider />
          <h3 class="title">规则设置</h3>
          <a-form-model-item
            style="padding-bottom: 10px"
            label="每人限购"
            prop="self_limit_num"
            help="每件商品每人最多可购买数量限制，不填时默认不限制。（商品开启了限购时，取两者最小值）"
          >
            <div class="flex maxWidth" style="padding-bottom: 10px">
              <a-input-number style="flex: 1" v-model="form.self_limit_num" :min="0" :precision="0" />
              <div class="slot">件</div>
            </div>
          </a-form-model-item>
          <a-form-model-item
            style="padding-bottom: 10px"
            label="每单限购"
            prop="order_limit_num"
            help="每单最多可购买商品数量，不填时不限制"
          >
            <div class="flex maxWidth" style="padding-bottom: 10px">
              <a-input-number style="flex: 1" v-model="form.order_limit_num" :min="0" :precision="0" />
              <div class="slot">件</div>
            </div>
          </a-form-model-item>
          <a-form-model-item label="是否使用优惠券" prop="is_use_coupon">
            <a-radio-group v-model="form.is_use_coupon">
              <a-radio value="1">允许</a-radio>
              <a-radio value="0">不允许</a-radio>
            </a-radio-group>
          </a-form-model-item>

          <a-divider />
          <h3 class="title">活动商品</h3>

          <a-form-model-item label="选择商品" required>
            <a-button style="margin-bottom: 10px" type="primary" @click="openGoods"> 添加商品 </a-button>

            <a-table :data-source="form.goods" :columns="columns" :pagination="false" :scroll="{ x: 'max-content' }">
              <div slot="content" slot-scope="scope, text">
                <div class="imgTxt">
                  <div class="img">
                    <img :src="text.cover_pic" alt="" />
                  </div>
                  <div class="txt">
                    <a-tooltip>
                      <template #title>{{ text.name }}</template>
                      <div class="name">{{ text.name }}</div>
                    </a-tooltip>
                  </div>
                </div>
              </div>

              <div slot="virtual_sales" slot-scope="scope, text">
                <a-input-number size="small" v-model="text.virtual_sales" :min="0" :precision="0" />
              </div>

              <div slot="virtual_num" slot-scope="scope, text">
                <a-input-number size="small" v-model="text.virtual_num" :min="0" :precision="0" />
              </div>

              <div slot="seckillNum" slot-scope="scope, text">
                <template v-if="text.use_attr === '1'">
                  <span class="btnAttr" @click="setAttr(text)">设置秒杀库存</span>
                </template>
                <a-input-number size="small" v-else v-model="text.seckill_num" :min="0" :precision="0" />
              </div>

              <div slot="seckillPrice" slot-scope="scope, text">
                <template v-if="text.use_attr === '1'">
                  <span class="btnAttr" @click="setAttr(text)">设置秒杀价格</span>
                </template>
                <a-input-number size="small" v-else v-model="text.seckill_price" :min="0" :precision="2" />
              </div>

              <div slot="actions" slot-scope="scope, text">
                <a-button type="link" @click="remove(text)" size="small">删除</a-button>
              </div>
            </a-table>
          </a-form-model-item>

          <div class="btnBox">
            <a-button v-loading="btnLoading" :disabled="disabled" type="primary" @click="onSubmit"> 提交 </a-button>
            <a-button style="margin-left: 10px" @click="$router.go(-1)"> 取消 </a-button>
          </div>
        </a-form-model>
      </a-card>

      <popGoods :selectedList="form.goods" @onOk="selectGoods" ref="popGoods"></popGoods>
      <popAttr @onOk="setAttrPop" ref="popAttr" :item="item"></popAttr>
    </page-header-wrapper>
  </div>
</template>

<script>
import { Save, Info } from '@/api/marketing/seckill'
import popGoods from './components/goods.vue'
import popAttr from './components/attr.vue'

export default {
  components: {
    popGoods,
    popAttr,
  },

  data() {
    return {
      btnLoading: false,
      disabled: false,

      item: null,

      columns: [
        {
          title: 'ID',
          dataIndex: 'id',
          key: 'id',
          width: 60,
        },
        {
          title: '商品名称',
          dataIndex: 'content',
          scopedSlots: { customRender: 'content' },
        },
        {
          title: '售价',
          dataIndex: 'price',
          key: 'price',
          ellipsis: true,
          sorter: (a, b) => a.price - b.price,
        },
        {
          title: '总库存',
          dataIndex: 'goods_num',
          key: 'goods_num',
          ellipsis: true,
          sorter: (a, b) => a.goods_num - b.goods_num,
        },
        // {
        //   title: '秒杀已售',
        //   dataIndex: 'sale_num',
        //   key: 'sale_num',
        //   ellipsis: true,
        //   sorter: (a, b) => a.sale_num - b.sale_num,
        // },
        // {
        //   title: '虚拟秒杀销量',
        //   dataIndex: 'virtual_sales',
        //   scopedSlots: { customRender: 'virtual_sales' },
        //   sorter: (a, b) => a.virtual_sales - b.virtual_sales,
        // },
        // {
        //   title: '虚拟秒杀库存',
        //   dataIndex: 'virtual_num',
        //   scopedSlots: { customRender: 'virtual_num' },
        // },
        {
          title: '秒杀库存',
          dataIndex: 'seckillNum',
          scopedSlots: { customRender: 'seckillNum' },
        },
        {
          title: '秒杀价格',
          dataIndex: 'seckillPrice',
          scopedSlots: { customRender: 'seckillPrice' },
        },
        {
          title: '操作',
          dataIndex: 'actions',
          scopedSlots: { customRender: 'actions' },
          fixed: 'right',
        },
      ],

      form: {
        id: '',
        name: '',
        queryTime: [],
        self_limit_num: '0',
        order_limit_num: '0',
        is_use_coupon: '1',
        goods: [],
      },

      // 支付宝验证规则
      formRules: {
        name: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        queryTime: [
          {
            required: true,
            message: '请选择活动时间',
            trigger: 'change',
          },
        ],
        self_limit_num: [{ required: true, message: '请选择每人限购数量', trigger: 'blur' }],
        order_limit_num: [{ required: true, message: '请选择每单限购数量', trigger: 'blur' }],
        is_use_coupon: [{ required: true, message: '请选择是否使用优惠券', trigger: 'change' }],
      },
    }
  },

  methods: {
    openGoods() {
      this.$nextTick(() => {
        this.$refs.popGoods.visible = true
      })
    },

    selectGoods(list) {
      this.form.goods.push(...list)
    },

    remove(item) {
      let { goods } = this.form,
        index = goods.findIndex((el) => el.id === item.id)

      goods.splice(index, 1)
    },

    setAttr(item) {
      this.item = item
      this.$refs.popAttr.visible = true
    },

    setAttrPop(item) {
      let { goods } = this.form,
        index = goods.findIndex((el) => el.id === item.id)

      this.$set(goods[index], 'attr', item.attr)
    },

    // 点击提交
    onSubmit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form))
          if (!form.goods.length) return this.$message.error('请选择活动商品~')

          form.goods = form.goods.map((el) => {
            if (el.attr) {
              el.attr = el.attr
                .filter((e) => e.checked)
                .map((e) => {
                  delete e.checked
                  return e
                })
            }
            return el
          })

          form.start_time = form.queryTime[0]
          form.end_time = form.queryTime[1]
          delete form.queryTime

          this.btnLoading = true
          const res = await Save(form)

          this.btnLoading = false

          if (!res.code) {
            this.$message.success(res.msg)
            this.$router.back()
            return
          }

          this.$message.error(res.msg)
        } else {
          return false
        }
      })
    },
  },

  async mounted() {
    let id = this.$route.query.id

    if (!id) return
    const hide = this.$message.loading('请稍等', 0)

    let res = await Info({
      id,
    })
    hide()
    if (res.code) return this.$message.error(res.msg)
    let { name, self_limit_num, order_limit_num, is_use_coupon, start_time, end_time } = res.data.activity,
      { activity_goods: goods } = res.data

    goods = goods.map((el) => {
      if (el.attr) {
        el.attr.forEach((e) => {
          e.checked = true
        })
      }
      return el
    })

    this.form = {
      id,
      name,
      queryTime: [start_time, end_time],
      self_limit_num,
      order_limit_num,
      is_use_coupon: String(is_use_coupon),
      goods,
    }
  },
}
</script>

<style lang="less" scoped>
.title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 14px;
  font-weight: bold;
}

.flex {
  display: flex;

  .slot {
    border: 1px solid #d9d9d9;
    border-left: 0;
    border-radius: 0 4px 4px 0;
    height: 32px;
    width: 32px;
    background: rgba(247, 247, 247, 1);
    text-align: center;
  }
}

.maxWidth {
  width: 480px;
}

.imgTxt {
  display: flex;
  max-width: 250px;

  .img {
    width: 50px;
    height: 50px;

    img {
      display: block;
      width: 100%;
      height: 100%;
    }
  }

  .txt {
    flex: 1;
    overflow: hidden;
    margin-left: 10px;
  }

  .name {
    display: -webkit-box;
    white-space: normal;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
    overflow: hidden;
  }
}

.btnAttr {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #333;
  font-size: 12px;
  width: 90px;
  height: 24px;
  border: 1px solid #d9d9d9;
  box-sizing: border-box;
  cursor: pointer;
}

.btnBox {
  text-align: center;
}
</style>
